package dao;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import modelo.Caracteristicaxsalon;
import modelo.Domicilio;
import modelo.Imagenesxsalon;
import modelo.Persona;
import modelo.Salon;
import modelo.Telefonosalon;
import modelo.Tipoevento;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import controllers.UsuarioBean;
import util.HibernateUtil;

public class SalonDao implements Serializable {

	private static final long serialVersionUID = -5474035676702451824L;

	private Session session;
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public SalonDao() {
		super();
	}

	public List<Salon> obtenerSalones() {
		session = sessionFactory.openSession();

		Criteria cr = session.createCriteria(Salon.class);
		// .setFetchMode("servicioadicionalxsalons", FetchMode.JOIN);

		List<Salon> results = cr.list();
		session.close();
		return results;
	}

	public List<Salon> obtenerSalonesProp() {
                
                FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
                HttpSession sessionActual = (HttpSession) context.getExternalContext().getSession(false);
                Integer nB = null;
                
                if (sessionActual!= null)
                {  nB = Integer.parseInt(sessionActual.getAttribute("persona").toString());             }
                else
                {
                	nB=2;
                	
                }

                List<Salon> results=new ArrayList<Salon>();
                
                session = sessionFactory.openSession();
        
                Criteria cr = session.createCriteria(Salon.class)
                                        .add(Restrictions.eq("persona.idPersona", nB));
//              .setFetchMode("servicioadicionalxsalons", FetchMode.JOIN);
                
                results = cr.list();
                session.close();
                
                return results;
        }
	
	public void guardarSalon(Salon salon, Domicilio dom,
			List<Tipoevento> eventos, List<Caracteristicaxsalon> c,
			List<Telefonosalon> t, List<Imagenesxsalon> imagenes) {
		
		Persona p = new Persona();
                FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
                HttpSession sessionActual = (HttpSession) context.getExternalContext().getSession(false);
                Integer nB = Integer.parseInt(sessionActual.getAttribute("persona").toString());
                p.setIdPersona(nB);
                salon.setPersona(p);
		
		session = sessionFactory.openSession();
		session.beginTransaction();

		try {

			session.save(dom);
			Long idDomicilio = ((BigInteger) session.createSQLQuery(
					"SELECT LAST_INSERT_ID()").uniqueResult()).longValue();
			int anInt = new BigDecimal(idDomicilio).intValueExact();
			dom.setIdDomicilio(anInt);

			// agrego domicilio al salon
			salon.setDomicilio(dom);

			// guardo los tipos de eventos del salon
			Set<Tipoevento> tipoEv = new HashSet<Tipoevento>();

			Iterator<Tipoevento> i = eventos.iterator();
			while (i.hasNext()) {
				Tipoevento te = (Tipoevento) i.next();
				tipoEv.add(te);
			}

			salon.setTipoeventos(tipoEv);
			

			// guardo el salon
			session.save(salon);

			// obtengo el id del salon para despues guardar las caracteristicas
			// por salon
			Long sal = ((BigInteger) session.createSQLQuery(
					"SELECT LAST_INSERT_ID()").uniqueResult()).longValue();
			int idSalon = new BigDecimal(sal).intValueExact();

			// guardo los telefonos por salon
			Iterator<Telefonosalon> ite = t.iterator();
			while (ite.hasNext()) {
				Telefonosalon ts = (Telefonosalon) ite.next();
				ts.setSalon(salon);
				salon.getTelefonosalons().add(ts);
				session.save(ts);
			}

			// guardo las caracteristicas por salon a mano jaja
			Query query = session
					.createSQLQuery("INSERT INTO caracteristicaxsalon (idCaracteristica, idSalon, descripcionCaracteristica) VALUES (:valor1, :valor2, :valor3)");

			Iterator<Caracteristicaxsalon> it = c.iterator();
			while (it.hasNext()) {
				Caracteristicaxsalon ca = (Caracteristicaxsalon) it.next();
				query.setParameter("valor1", ca.getCaracteristica()
						.getIdCaracteristica());
				query.setParameter("valor2", idSalon);
				query.setParameter("valor3", ca.getCaracteristica());
				query.executeUpdate();

			}

			// guardo las caracteristicas por salon a mano jaja
			Query queryIm = session
					.createSQLQuery("INSERT INTO imagenesxsalon (idSalon, imagen) VALUES (:valor1, :valor2)");

			Iterator<Imagenesxsalon> it1 = imagenes.iterator();
			while (it1.hasNext()) {
				Imagenesxsalon im = (Imagenesxsalon) it1.next();
				queryIm.setParameter("valor1", idSalon);
				queryIm.setParameter("valor2", im.getImagen());
				queryIm.executeUpdate();
			}

			session.getTransaction().commit();

		} catch (Exception e) {
			e.getCause();
			e.getMessage();
			session.getTransaction().rollback();
		} finally {
			session.close();
		}

	}
	
	public Salon obtenerSalon(Integer salonSel)
	{   
	
        session = sessionFactory.openSession();
        
        Criteria cr = session.createCriteria(Salon.class)
                                .add(Restrictions.eq("idSalon", salonSel));
//      .setFetchMode("servicioadicionalxsalons", FetchMode.JOIN);
        
        List<Salon>results = cr.list();
        session.close();		
		
		return results.get(0);
	}	

}
